package com.heihei.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * web拦截器设置
 *
 * @author duanhengfei
 * @version 1.0
 * @date 2020/6/28 22:11
 * @since JDK1.8
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //定义用户信息服务（查询用户信息）
    @Bean
    public UserDetailsService userDetailsService(){
        //基于内存的UserDetails
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;
    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        //不需要编码的密码编码对象
        return NoOpPasswordEncoder.getInstance();
    }


    //安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/resource/r1").hasAnyAuthority("p1")
                .antMatchers("/resource/r2").hasAnyAuthority("p2")
                .antMatchers("/resource/**").authenticated()   //所有 /r/** 的请求，必须认证通过才能访问
                .anyRequest().permitAll()  //其他资源一率放行
                .and()
                .formLogin() //允许表单登录
                .successForwardUrl("/login-success");  //自定义登录成功的页面地址
    }
}